<template>
  <div
    class="adverse"
    v-loading="loading"
    element-loading-background="rgba(255, 255, 255, 0)"
  >
    <el-form ref="form" label-width="120px" class="form">
      <el-form-item label="轮播图">
        <div class="banner_box">
          <div
            class="banner_item image"
            v-for="(item, index) in bannerList"
            :key="index"
          >
            <el-image
              style="border-radius: 4px; width: 100%; height: 100%"
              :src="item.link"
              fit="cover"
            ></el-image>

            <div class="tips_wrap" @click="handleChangeBanner(item, index)">
              <span class="name">更换轮播图</span>
              <span class="tips">750*450</span>
              <div @click.stop="handleDelete(index)" class="delete_box">
                <i class="el-icon-delete"></i>
              </div>
            </div>
          </div>
          <div class="banner_item" @click="handleUploadBannerShow">
            <i style="font-size: 30px" class="el-icon-plus"></i>
            <span style="font-size: 14px; color: #999; margin-top: 5px"
              >添加轮播图</span
            >
          </div>
        </div>
      </el-form-item>
      <el-form-item label="活动闪屏广告">
        <div>
          <el-switch
            @change="handleSplashScreenEnabled"
            v-model="adDetail.splashScreenEnabled"
          >
          </el-switch>
        </div>
      </el-form-item>
      <el-form-item label="广告设置" v-if="adDetail.splashScreenEnabled">
        <div class="upload_box">
          <upload
            :imageUrl="splashLink"
            @handleSuccess="handleSuccess1"
            type="BG_IMAGE"
            custom="custom"
          ></upload>
          <div @click="handleDefault1" class="default1">默认</div>
        </div>
      </el-form-item>
      <el-form-item label="输入网址" v-if="adDetail.splashScreenEnabled">
        <div class="input_box">
          <el-input
            v-model="splashTargetLink"
            placeholder="请输入广告跳转网址"
            @change="handleSplashTargetLink"
          ></el-input>
        </div>
      </el-form-item>
      <el-form-item label="广告等待时间" v-if="adDetail.splashScreenEnabled">
        <div class="input_box">
          <el-input
            v-model="adDetail.splashScreenWaitSecond"
            placeholder="请输入广告等待时间"
            @change="handleSplashWaitTime"
          ></el-input>
        </div>
      </el-form-item>
      <el-form-item label="投票提示广告">
        <div>
          <el-switch
            @change="handleVotingLinkEnabled"
            v-model="adDetail.votingLinkEnabled"
          >
          </el-switch>
        </div>
      </el-form-item>
      <el-form-item label="广告设置" v-if="adDetail.votingLinkEnabled">
        <div class="upload_box">
          <upload
            type="BG_IMAGE"
            custom="custom"
            :imageUrl="voteLink"
            @handleSuccess="handleSuccess2"
            :styleObject="{ width: '240px', height: '160px' }"
            size="622*380"
          ></upload>
          <div @click="handleDefault2" class="default2">默认</div>
        </div>
      </el-form-item>
      <el-form-item label="输入网址" v-if="adDetail.votingLinkEnabled">
        <div class="input_box">
          <el-input
            v-model="voteTargetLink"
            placeholder="请输入广告跳转网址"
            @change="handleVoteTargetLink"
          ></el-input>
        </div>
      </el-form-item>
    </el-form>
    <el-dialog
      :modal-append-to-body="false"
      :visible.sync="uploadBannerShow"
      width="800px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @close="handleClose"
      custom-class="banners_box"
    >
      <div class="banner_pop_wrap">
        <div class="left_wrap">
          <ul class="left_box">
            <li
              v-for="(item, index) in list"
              :key="index"
              @click="handleClick(item)"
              :class="{ active: currentType === item.type }"
            >
              {{ item.name }}
            </li>
          </ul>
          <div class="upload_btn_wrap">
            <el-upload
              class="upload-demo"
              :on-success="handleSuccess3"
              :before-upload="beforeUpload"
              name="multipartFile"
              :headers="headers"
              :multiple="false"
              :action="cfg.baseUrl + '/resource/upload?type=BANNER'"
              :show-file-list="false"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </div>
        </div>
        <div class="right_wrap">
          <div v-if="currentType == 'system'">
            <div class="head_wrap">
              <div
                @click="handleChangeHeadBanner(item.id)"
                :class="{ active: currentHeadId === item.id }"
                class="head_item"
                v-for="(item, index) in bannerHeadList"
                :key="index"
              >
                <span>{{ item.name }}</span>
              </div>
            </div>
            <div style="height: 500px">
              <template v-if="resourceList.length">
                <ul
                  class="infinite-list"
                  v-infinite-scroll="loadResource"
                  style="overflow: auto"
                  :infinite-scroll-disabled="disabledHead"
                >
                  <li
                    class="resource_item"
                    v-for="(ele, i) in resourceList"
                    :key="i"
                  >
                    <div class="img_wrap" @click="handleSelect(ele.link)">
                      <el-image
                        style="border-radius: 4px; width: 100%; height: 100%"
                        :src="ele.link"
                        fit="cover"
                      ></el-image>
                      <div v-if="ele.checked" class="currentUse">当前使用</div>
                    </div>
                  </li>
                </ul>
              </template>
            </div>
          </div>
          <div v-if="currentType == 'my'" style="height: 500px">
            <ul
              class="infinite-list"
              v-infinite-scroll="loadResource"
              style="overflow: auto"
              :infinite-scroll-disabled="disabled"
            >
              <li
                class="resource_item"
                v-for="(ele, i) in resourceList"
                :key="i"
              >
                <div class="img_wrap" @click="handleSelect(ele.link)">
                  <el-image
                    style="border-radius: 4px; width: 100%; height: 100%"
                    :src="ele.link"
                    fit="cover"
                  ></el-image>
                  <div v-if="ele.checked" class="currentUse">当前使用</div>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import upload from "@/components/upload";
import cfg from "@/config";
import { mapGetters } from "vuex";
import { LgetItem } from "@/utils/storage";
export default {
  components: {
    upload,
  },
  data() {
    return {
      cfg,
      adDetail: {},
      voteTargetLink: "",
      voteLink: "",
      splashLink: "",
      splashTargetLink: "",
      uploadBannerShow: false,
      bannerList: [],
      resourceList: [],
      list: [
        { name: "系统推荐", type: "system" },
        { name: "我的轮播", type: "my" },
      ],
      currentType: "system",
      query: {
        pageNum: 1,
        pageSize: 20,
        tagId: null,
        type: "BANNER",
        userId: 0,
      },
      disabled: false,
      disabledHead: false,
      currentBannerLink: "", //用户更换轮播图的一个记录
      currentBannerIndex: "", //记录当前是哪个轮播
      bannerHeadList: [],
      currentHeadId: 0,
      headers: { Token: LgetItem("jwtToken") },
    };
  },
  computed: {
    ...mapGetters("status", {
      loading: "loading",
    }),
  },
  created() {
    this.getAdDetail();
    //接口获取head的时候再改
    // this.currentHeadId = this.bannerHeadList[0].id;
  },
  methods: {
    //点击head找到对应的图片资源
    handleChangeHeadBanner(id) {
      console.log(id);
      this.currentHeadId = id;
      //修改id
      this.resourceList = [];
      this.query.tagId = id; //id
      this.query.pageNum = 1;
      this.disabledHead = false;
      this.loadResource();
    },
    //获取资源图片
    getResourceBanner() {
      this.$api("resource.getResource", this.query).then((res) => {
        this.resourceList.push(...res.data);
        if (res.data.length >= this.query.pageSize) {
          //就不能再+1了
          this.query.pageNum++;
        } else {
          if (this.currentType === "system") {
            this.disabledHead = true;
          }
          if (this.currentType === "my") {
            this.disabled = true;
          }
        }
        this.bannerList.forEach((item) => {
          this.resourceList.forEach((ele) => {
            if (item.link === ele.link) {
              ele.checked = true;
            }
          });
        });
        this.uploadBannerShow = true;
      });
    },
    //更换轮播图
    handleChangeBanner(item, index) {
      this.currentBannerLink = item.link;
      this.currentBannerIndex = index;

      this.loadResource();
    },
    loadResource() {
      this.getResourceBanner();
    },
    handleUploadBannerShow() {
      this.loadResource();
      this.getResourceTag();
    },
    //获取资源标签
    getResourceTag() {
      this.$api("resource.getResourceTag", {
        type: "BANNER",
      }).then((res) => {
        console.log(res);
        this.bannerHeadList = res;
        this.bannerHeadList.unshift({
          name: "全部",
          id: "",
        });
      });
    },
    beforeUpload(file) {
      console.log(file);
      return true;
    },
    //删除banner
    handleDelete(index) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.bannerList.splice(index, 1);
          this.saveApi();
        })
        .catch(() => {});
    },
    handleSelect(link) {
      //判断是新增一个banner还是更换
      if (this.currentBannerLink) {
        this.bannerList[this.currentBannerIndex].link = link;
      } else {
        this.bannerList.push({
          link,
          targetLink: "",
        });
      }
      this.uploadBannerShow = false;
      this.saveApi();
    },
    handleClose() {
      this.resourceList = [];
      this.currentType = "system";
      this.query.pageNum = 1;
      this.currentBannerLink = "";
      this.currentBannerIndex = "";
      //之前一直不明白为什么滑动到底部之后关闭dialog，然后在打开，始终不执行loadResource
      //原来是下面这个属性变成了true
      this.disabled = false;
    },
    //轮播图
    handleSuccess3(res, file) {
      console.log(file);
      console.log(res);
      this.resourceList.unshift({
        link: res.data,
      });
    },
    handleClick(item) {
      this.resourceList = [];
      this.query.pageNum = 1;
      this.currentType = item.type;
      this.currentHeadId = this.bannerHeadList[0].id;
      this.disabled = false;
      this.disabledHead = false;
      //根据type类型来决定获取资源的时候是否需要传递userId，tagId
      //如果点击系统推荐，当前是全部的时候tagId不传
      if (this.currentType === "system") {
        this.query.tagId = null;
        this.query.userId = 0;
        this.loadResource();
      } else {
        //暂时传0，因为还没有做登录
        this.query.tagId = null;
        this.query.userId = 1;
      }
    },
    getAdDetail() {
      this.$api("vote.getAdDetail", {
        voteId: this.$route.query.id,
      }).then((res) => {
        this.adDetail = res;
        //投票提示广告
        if (this.adDetail.votingLink) {
          this.voteLink = this.adDetail.votingLink.link;
          this.voteTargetLink = this.adDetail.votingLink.targetLink;
        }
        //活动闪屏广告
        if (this.adDetail.splashScreenLink) {
          this.splashLink = this.adDetail.splashScreenLink.link;
          this.splashTargetLink = this.adDetail.splashScreenLink.targetLink;
        }
        if (this.adDetail.bannerLink) {
          this.bannerList = this.adDetail.bannerLink;
        }
      });
    },
    //活动闪屏广告
    handleSuccess1(link) {
      this.splashLink = link;
      this.saveApi();
    },
    //投票提示广告
    handleSuccess2(link) {
      this.voteLink = link;
      this.saveApi();
    },
    handleSave() {
      this.adDetail.votingLink = {
        link: this.voteLink,
        targetLink: this.voteTargetLink,
      };
      this.adDetail.splashScreenLink = {
        link: this.splashLink,
        targetLink: this.splashTargetLink,
      };
      this.adDetail.voteId = this.$route.query.id;
      this.$api("vote.saveAdDetail", this.adDetail).then((res) => {
        console.log(res);
      });
    },
    //修改立即保存
    saveApi() {
      this.adDetail.votingLink = {
        link: this.voteLink,
        targetLink: this.voteTargetLink.trim(),
      };
      this.adDetail.splashScreenLink = {
        link: this.splashLink,
        targetLink: this.splashTargetLink.trim(),
      };
      this.adDetail.bannerLink = this.bannerList;
      this.adDetail.voteId = this.$route.query.id;
      this.$api("vote.saveAdDetail", this.adDetail).then((res) => {
        this.$store.commit("status/SET_URL", new Date().getTime());
        console.log(res);

        this.$message({
          message: "保存成功",
          type: "success",
          duration: 1000,
        });
      });
    },
    //切换闪屏广告
    handleSplashScreenEnabled() {
      this.saveApi();
    },
    //切换闪屏广告
    handleVotingLinkEnabled() {
      this.saveApi();
    },
    handleSplashWaitTime() {
      if (
        this.adDetail.splashScreenWaitSecond >= 1 &&
        this.adDetail.splashScreenWaitSecond <= 10
      ) {
        this.saveApi();
      } else {
        this.$message({
          message: "闪屏广告等待时间范围1~10秒",
          type: "error",
          duration: 2000,
        });
      }
    },
    //广告跳转网址
    handleVoteTargetLink() {
      this.saveApi();
    },
    handleSplashTargetLink() {
      this.saveApi();
    },
    handleDefault1() {
      this.splashLink = "";
      this.saveApi();
    },
    handleDefault2() {
      this.voteLink = "";
      this.saveApi();
    },
  },
};
</script>

<style lang="scss" scoped>
.adverse {
  width: 820px;
  min-height: 550px;
  padding-bottom: 30px;
  ::v-deep.banners_box {
    margin: 0;
    margin-left: 600px;
  }
  ::v-deep.el-form-item__label {
    padding-right: 20px;
  }
  ::v-deep.el-dialog__body {
    padding: 30px 0;
  }
  .ad_title {
    font-size: 14px;
    margin-right: 40px;
  }
  .upload_box {
    position: relative;
    .default1 {
      position: absolute;
      left: 150px;
      top: calc(50% - 20px);
      transform: translateY(-50%);
      cursor: pointer;
      color: $themeColor;
    }
    .default2 {
      position: absolute;
      left: 270px;
      top: calc(50% - 20px);
      transform: translateY(-50%);
      cursor: pointer;
      color: $themeColor;
    }
  }
  .input_box {
    width: 300px;
    ::v-deep.el-input__inner {
      border-radius: 40px;
    }
  }
  .banner_box {
    display: flex;
    margin-right: 15px;
    flex-wrap: wrap;
    ::v-deep.el-dialog__body {
      padding: 20px 0;
    }
    .banner_item {
      border: 1px dashed #ccc;
      border-radius: 4px;
      width: 180px;
      height: 110px;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      cursor: pointer;
      margin-right: 15px;
      margin-top: 15px;
      position: relative;
      .tips_wrap {
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
        z-index: 6;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        border-radius: 4px;
        background: rgba(0, 0, 0, 0);
        opacity: 0;
        .delete_box {
          position: absolute;
          right: 5px;
          top: 5px;
          opacity: 0;
          font-size: 13px;
        }
        &:hover {
          .delete_box {
            opacity: 1;
            color: #fff;
            &:hover {
              color: #ee6869;
            }
          }
          opacity: 1;
          background: rgba(0, 0, 0, 0.5);
          .name {
            color: $themeColor;
            font-size: 13px;
          }
          .tips {
            color: #fff;
            font-size: 13px;
          }
        }
      }
    }
  }
  // .voteAd {
  //   margin-top: 40px;
  // }
}

.banner_pop_wrap {
  display: flex;
  height: 500px;
  .left_wrap {
    flex: 0 0 100px;
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    .upload_btn_wrap {
      text-align: center;
      padding: 40px 0;
    }
    .left_box {
      text-align: center;
      li {
        line-height: 30px;
        cursor: pointer;
        margin: 10px 0;
        font-size: 13px;
      }

      .active {
        background: #3398ff;
        color: #fff;
      }
    }
  }
  .right_wrap {
    flex: 1;
    background: #f5f6f8;
    .head_wrap {
      display: flex;
      background-color: #fff;
      .head_item {
        padding: 5px 20px;
        font-weight: 500;
        font-size: 15px;
        cursor: pointer;
        &.active {
          color: $themeColor;
        }
      }
    }
    .infinite-list {
      height: 500px;
      padding: 10px;
      .resource_item {
        width: 33.333%;
        display: inline-block;
        padding: 10px;
        height: 140px;
        cursor: pointer;
        .img_wrap {
          position: relative;
          width: 100%;
          height: 100%;
          overflow: hidden;
          .currentUse {
            position: absolute;
            left: -24px;
            top: 10px;
            background-color: #29cc7a;
            color: #fff;
            z-index: 2;
            font-size: 11px;
            text-align: center;
            padding: 5px 20px;
            transform: rotate(-45deg);
            line-height: 1;
          }
        }
      }
    }
  }
}
</style>
